<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model.trim="search_form.name" placeholder="菜单名称" clearable>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="get_menu_list">搜索</el-button>
        <el-button @click="handle_reset">重置</el-button>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          @click="dialog_visible = true"
          v-has="'system:menu:add'"
          >新增</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      :data="menu_list"
      tooltip-effect="dark"
      style="width: 100%"
      border
      stripe
    >

      <el-table-column prop="id" label="菜单ID"> </el-table-column>
      <el-table-column prop="name" label="菜单名称">
      </el-table-column>
      <el-table-column prop="path" label="路由地址"> </el-table-column>
      <el-table-column prop="component" label="组件路径"> </el-table-column>
      <el-table-column prop="perms" label="权限标识"> </el-table-column>
      <el-table-column prop="type" label="菜单类型">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.type === 0" type="info"
            >目录</el-tag
          >
          <el-tag size="small" v-else-if="scope.row.type === 1" type="success"
            >菜单</el-tag
          >
          <el-tag size="small" v-else-if="scope.row.type === 2" type="primary"
            >按钮</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.status === 1" type="success"
            >启用</el-tag
          >
          <el-tag size="small" v-else-if="scope.row.status === 0" type="danger"
            >禁用</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="order_num" label="排序">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="edit_handle(scope.row.id)"
            v-has="'system:menu:edit'"
            >编辑</el-button
          >
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm
              title="确定删除吗？"
              @confirm="del_handle(scope.row.id)"
            >
              <el-button
                type="text"
                slot="reference"
                v-has="'system:menu:delete'"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handle_size_change"
      @current-change="handle_current_change"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="page_num"
      :page-size="page_size"
      :total="total"
    >
    </el-pagination>

    <!--新增对话框-->
    <el-dialog
      title="提示"
      :visible.sync="dialog_visible"
      width="600px"
      :before-close="handle_close"
    >
      <el-form :model="menu_form" :rules="edit_form_rules" ref="menu_form">
        <el-form-item label="父菜单ID" prop="parent_id" label-width="100px">
          <el-input
            v-model="menu_form.parent_id"
            type="number"
            placeholder="默认为0（顶级菜单）"
          ></el-input>
        </el-form-item>

        <el-form-item label="菜单名称" prop="name" label-width="100px">
          <el-input v-model.trim="menu_form.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="路由地址" prop="path" label-width="100px">
          <el-input v-model.trim="menu_form.path" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="组件路径" prop="component" label-width="100px">
          <el-input v-model.trim="menu_form.component" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="权限标识" prop="perms" label-width="100px">
          <el-input v-model.trim="menu_form.perms" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="菜单类型" prop="type" label-width="100px">
          <el-select v-model="menu_form.type" placeholder="请选择菜单类型">
            <el-option label="目录" :value="0"></el-option>
            <el-option label="菜单" :value="1"></el-option>
            <el-option label="按钮" :value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图标" prop="icon" label-width="100px">
          <el-input v-model.trim="menu_form.icon" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="排序" prop="order_num" label-width="100px">
          <el-input
            v-model="menu_form.order_num"
            type="number"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status" label-width="100px">
          <el-radio-group v-model="menu_form.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset_form('menu_form')">取 消</el-button>
        <el-button type="primary" @click="submit_form('menu_form')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import menuApi from "@/api/sys-menu.js";
export default {
  name: "Menu",
  data() {
    return {
      search_form: {
        name: "",
      },
      total: 0,
      page_size: 10,
      page_num: 1,

      dialog_visible: false,
      menu_form: {
        parent_id: 0,
        status: 1,
        order_num: 0,
      },

      menu_list: [],

      edit_form_rules: {
        name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
        type: [{ required: true, message: "请选择菜单类型", trigger: "blur" }],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
      },


    };
  },
  created() {
    this.get_menu_list();
  },
  methods: {
    handle_size_change(val) {
      this.page_size = val;
      this.get_menu_list();
    },
    handle_current_change(val) {
      this.page_num = val;
      this.get_menu_list();
    },

    reset_form(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.dialog_visible = false;
      this.menu_form = {
        parent_id: 0,
        status: 1,
        order_num: 0,
      };
    },
    handle_close() {
      this.reset_form("menu_form");
    },

    get_menu_list() {
      menuApi
        .list({
          name: this.search_form.name,
          page_num: this.page_num,
          page_size: this.page_size,
        })
        .then((res) => {
          if (res && res.data) {
            this.menu_list = res.data.records || [];
            this.page_size = res.data.size || this.page_size;
            this.page_num = res.data.current || this.page_num;
            this.total = res.data.total || 0;
          } else {
            this.menu_list = [];
            this.total = 0;
          }
        })
        .catch((error) => {
          console.error("获取菜单列表失败:", error);
          this.menu_list = [];
          this.total = 0;
        });
    },
    // 重置搜索条件
    handle_reset() {
      this.search_form = {
        name: ''
      };
      this.get_menu_list();
    },

    submit_form(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const api = this.menu_form.id ? menuApi.update : menuApi.add;
          api(this.menu_form).then((res) => {
            this.$message({
              showClose: true,
              message: this.menu_form.id ? "更新成功" : "创建成功",
              type: "success",
              onClose: () => {
                // 代码移到下一行
              },
            });
            this.get_menu_list();
            this.dialog_visible = false;
          });
        } else {
          return false;
        }
      });
    },
    edit_handle(id) {
      menuApi.detail(id).then((res) => {
        this.menu_form = res.data;
        this.dialog_visible = true;
      });
    },
    del_handle(id) {
      const ids = id ? [id] : this.multiple_selection.map((row) => row.id);
      // 根据api文件，delete方法需要单个id，需要循环调用
      if (ids.length === 1) {
        menuApi.delete(ids[0]).then(() => {
          this.$message({
            showClose: true,
            message: "操作成功",
            type: "success",
            onClose: () => {
              // 代码移到下一行
            },
          });
          this.get_menu_list();
        });
      } else if (ids.length > 1) {
        // 对于多个id，使用Promise.all处理批量删除
        Promise.all(ids.map((itemId) => menuApi.delete(itemId))).then(() => {
          this.$message({
            showClose: true,
            message: "批量删除成功",
            type: "success",
            onClose: () => {
              // 代码移到下一行
            },
          });
          this.get_menu_list();
        });
      }
    },
  },
};
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
}
</style>